package pro.model.data.server;

import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
import pro.model.data.HighScore;
import pro.resources.*;

/**
 * @author  sangwo.y
 */
public class HighScoreServer extends UnicastRemoteObject implements IHighScoreServer {

	private List<HighScore.Item> allScores;
	private List<HighScore.Item> newScores;
	private HighScore dumHighScore;
	private int newItems = 0;
	
	private final int ITEMS_COUNT_PERSISTANCE_TRIGGER = 1; 
	
	public HighScoreServer() throws RemoteException {
		super();
	}

	public void initServer() {
		allScores = new ArrayList<HighScore.Item>();
		newScores = new ArrayList<HighScore.Item>();
		dumHighScore = new HighScore();
				
		BufferedReader br = null;
	      try {
	         br = new BufferedReader(new FileReader(
	        		 ResourceLocator.getInstance().getFile("serverscores.dat")));
	         String l1,l2,l3;
	         boolean moreToRead = true;
	         while (moreToRead) {
	        	 l1 = br.readLine();
	        	 l2 = br.readLine();
	        	 l3 = br.readLine();
	        	 if (l1==null) {
	        		 moreToRead=false;
	        	 } else {
	        		 HighScore.Item item = dumHighScore.new Item(l1, new Integer(l2), new Integer(l3));
	        		 allScores.add(item);
	        	 }
	         }
	         br.close();
	      } catch (Exception e) {
	    	  e.printStackTrace();
	      }

	}

	public Object[][] load() throws RemoteException {
		Object[][] tmp = new Object[allScores.size()][3];
		int count = 0;
		for (HighScore.Item hi: allScores) {
			tmp[count][0]=hi.getPlayer();
			tmp[count][1]=hi.getDuration();
			tmp[count][2]=hi.getScore();
			count++;
		}		
		return tmp;
	}

	public int store(String player, int duration, int score) throws RemoteException {
		newItems++;
		System.out.println(player+" "+duration+" "+score);
		HighScore.Item item = dumHighScore.new Item(player, duration, score);
		allScores.add(item);
		newScores.add(item);
		if (newItems>ITEMS_COUNT_PERSISTANCE_TRIGGER) {
			persistScores();
			newItems = 0;
			newScores.clear();
		}
		return allScores.size();	
	}
	
	private void persistScores() {
		 BufferedWriter bw = null;

	      try {
	         bw = new BufferedWriter(new FileWriter(
	        		 	ResourceLocator.getInstance().getFile("serverscores.dat"), true));
	         for (HighScore.Item item: newScores) {
			 	bw.write(item.getPlayer());	
			 	bw.newLine();
			 	bw.write(Integer.toString(item.getDuration()));	
			 	bw.newLine();
			 	bw.write(Integer.toString(item.getScore()));	
			 	bw.newLine();
	         }
			 bw.flush();
			 bw.close();
	      } catch (Exception e) {
	    	  e.printStackTrace();
	      }  

	}
	
	public static void main(String[] args) {
		if (System.getSecurityManager() == null) {
	            System.setSecurityManager(new RMISecurityManager());
	        }
	        
	        String name = "//localhost/IHighScoreServer";
	        try {
	            IHighScoreServer server = new HighScoreServer();
	            Naming.rebind(name, server);
	            System.out.println("Server <--- HighScoreServer Bound");
	            ((HighScoreServer)server).initServer();
	            System.out.println("Server <--- HighScoreServer Initialized");
	        } catch (Exception e) {
	            System.err.println("HighScoreServer Exception: " + 
	           	e.getMessage());
	           	e.printStackTrace();
	    }
	}
	

}
